/* 
    思路:1.在以索引为区间范围的[0,right]中查找,right指数组的最后一个索引,即length-1.
        mid=left+(right-left)/2(防止溢出越界)
        2.不断对比中值nums[mid]与target，若targer>nums[mid]，说明target在中值右面，缩小区间范围即left=mid+1；
            若targer<中值，说明target在中值左面，缩小区间范围即right=mid-1；
        3.若查找成功，则返回中值索引,即mid,查找失败则返回-1;
        4.注意：left<=right可防止空数组,同时等号可以允许单值数组;
 */
function search(nums: number[], target: number) {
    let left = 0;
    let right = nums.length - 1;
    while (left <= right) {
        let mid = Math.floor(left + (right - left) / 2);
        if (target === nums[mid]) {
            return mid;
        }else if(target < nums[mid]){
            right=mid-1;
        }else if(target > nums[mid]){
            left = mid+1;
        }
    }
    return -1;
}